import {
  getModelInfo
} from './chat_API/get_model_info';
import {
  handleInput,
  handleFocus,
  handleBlur
} from './chat_API/input_handler';
import {
  chooseImage,
  previewImage,
  removePreview
} from './chat_API/image_handler';
import {
  getAIResponse
} from './chat_API/ai_response';
import {
  copyToClipboard
} from './chat_API/clipboard_handler';
import {
  getChatHistory
} from './chat_API/chat_history.js';
const AudioUtils = require('./chat_API/baidu');
const audioUtils = new AudioUtils();
Page({
  data: {
    messages: [],
    inputValue: '',
    isFocused: false,
    sendIcon: 'https://kangkangkangkang.oss-cn-wuhan-lr.aliyuncs.com/%E5%BA%B7/chat/%E8%AF%AD%E9%9F%B3%E8%BE%93%E5%85%A5.png', // 初始为语音输入图标
    avatarUrl: '',
    modelInfo: null,
    conversationId: '', // 添加conversationId到数据中
    messageId: '', // 存储消息的 message_id
    previewImageUrl: '', // 添加预览图片的URL
    hasMore: true, // 是否有更多历史数据
    refreshHint: '下拉加载历史消息...', // 刷新提示语句
    firstMessageId: '', // 最早一条消息的 ID
    isPlaying: false, // 初始播放状态
    playIcon: 'https://kangkangkangkang.oss-cn-wuhan-lr.aliyuncs.com/%E5%BA%B7/chat/%E5%BC%80%E5%A7%8B.png', // 播放图标
    pauseIcon: 'https://kangkangkangkang.oss-cn-wuhan-lr.aliyuncs.com/%E5%BA%B7/chat/Pause.png', // 暂停图标
    currentIcon: 'https://kangkangkangkang.oss-cn-wuhan-lr.aliyuncs.com/%E5%BA%B7/chat/%E5%BC%80%E5%A7%8B.png', // 当前图标
    currentPlayingId: null // 当前正在播放的文本的唯一ID
  },

  onLoad() {
    getModelInfo(this); // 获取智能体模型信息
    const userInfo = wx.getStorageSync('userInfo');
    console.log('从登录页面传到chat页面的用户信息：', userInfo);
    this.setData({
      avatarUrl: userInfo.avatar,
    });

    audioUtils.checkToken(() => {
      this.setData({
        token: audioUtils.token
      });
    });
    // 初始化音频上下文
    this.audioContext = wx.createInnerAudioContext();
    this.audioContext.onEnded(() => {
      this.setData({
        isPlaying: false,
        currentIcon: this.data.playIcon,
        currentPlayingId: null // 结束播放时，清空当前播放的文本ID
      });
    });

    this.audioContext.onError((res) => {
      console.error('音频播放失败', res.errMsg);
      this.setData({
        isPlaying: false,
        currentIcon: this.data.playIcon,
        currentPlayingId: null // 播放出错时，清空当前播放的文本ID
      });
    });
  },
  onPullDownRefresh() {
    console.log('Pull down refresh triggered');
    if (this.data.hasMore) {
      this.setData({
        refreshHint: '加载更多消息...',
      });
      getChatHistory(this); // 调用独立模块的方法
    } else {
      // 如果没有更多消息，显示全部信息已展示完的提示
      this.setData({
        refreshHint: '已展示全部信息',
      });
      // 延迟清空提示语句
      setTimeout(() => {
        this.setData({
          refreshHint: '',
        });
      }, 2000);
    }
  },
  onInput(event) {
    handleInput(event, this);
  },
  onFocus() {
    handleFocus(this);
  },
  onBlur() {
    handleBlur(this);
  },
  handleSend() {
    if (this.data.inputValue.trim() || this.data.previewImageUrl) {
      this.sendMessage();
    } else {
      this.touchStart(); // 启动语音输入功能
    }
  },
  sendMessage() {
    if (this.data.inputValue.trim() === '' && !this.data.previewImageUrl) return;
    const messagesToSend = [];
    // 处理图片
    if (this.data.previewImageUrl) {
      messagesToSend.push({
        role: 'user',
        content: this.data.previewImageUrl,
        isImage: true,
      });
      this.setData({
        previewImageUrl: '', // 清空预览图片 URL
      });
    }
    // 处理文字
    if (this.data.inputValue.trim()) {
      messagesToSend.push({
        role: 'user',
        content: this.data.inputValue.trim(),
        isImage: false,
      });
      this.setData({
        inputValue: '', // 清空输入框
      });
    }
    this.setData({
      messages: [...this.data.messages, ...messagesToSend],
      sendIcon: true,
    });

    // 发送 AI 加载消息
    this.sendAiLoadingMessage();

    // 请求 AI 响应
    getAIResponse(
      messagesToSend.filter(message => !message.isImage).map(message => message.content).join('\n'),
      messagesToSend.find(message => message.isImage)?.content,
      this
    );
  },
  sendAiLoadingMessage() {
    const loadingMessage = {
      role: 'ai',
      content: '',
      isImage: false,
      displayContent: '',
      isLoading: true,
    };

    this.setData({
      messages: [...this.data.messages, loadingMessage],
    });
  },
  chooseImage() {
    chooseImage(this);
  },
  previewImage(event) {
    previewImage(event, this);
  },
  removePreview() {
    removePreview(this)
  },
  copyToClipboard(event) {
    copyToClipboard(event, this);
  },
  handleSuggestionTap(event) {
    const content = event.currentTarget.dataset.content;
    this.setData({
      inputValue: content,
    });
    this.sendMessage();
  },
  startNewConversation() {
    // 清空所有消息
    this.setData({
      messages: [], // 清空所有对话消息
      conversationId: '', // 清空会话ID
      messageId: '', // 清空消息ID
    });

    // 重新获取模型信息，模拟新的会话开始
    getModelInfo(this);

    // 提示用户新对话已开始
    wx.showToast({
      title: '新对话已开始',
      icon: 'success',
      duration: 2000
    });
  },
  onShareAppMessage: function (res) {
    if (res.from === 'button') {
      const imageUrl = res.target.dataset.imageUrl;
      return {
        title: 'AI聊天图片分享',
        path: '/pages/chat/chat', // 指定分享的页面路径
        imageUrl: imageUrl, // 分享的图片 URL
      };
    }
    return {
      title: 'AI聊天',
      path: '/pages/chat/chat',
    };
  },
  wxParseTagATap(event) {
    //将不能转换为图片的路径直接点击可以预览
    const url = event.currentTarget.dataset.src;
    if (url && url.match(/\.(jpeg|jpg|gif|png)$/)) {
      wx.previewImage({
        current: url,
        urls: [url],
      });
    }
  },
  reloadContent(event) {
    const messageId = event.currentTarget.dataset.messageId; // 获取点击的消息 ID
    console.log('点击了重新加载图标，messageId:', messageId);
  },

  touchStart: function () {
    this.startY = 0; // 初始化起始位置
    this.setData({
      voice: true
    })
    audioUtils.startRecording();
  },
  touchMove: function (event) {
    const currentY = event.touches[0].pageY;
    if (this.startY - currentY > 50) { // 判断是否上滑超过50px
      console.log('上滑停止识别');
      audioUtils.stopRecording(() => {
        wx.showToast({
          title: '录音已取消',
          icon: 'none',
        });
      });
    }
  },
  touchEnd: function () {
    this.setData({
      voice: false
    })
    audioUtils.stopRecording(() => {
      audioUtils.recognizeSpeech(
        (result) => {
          this.setData({
            inputValue: result
          });
        },
        (error) => {
          console.log("识别失败", error);
        }
      );
    });
  },
  scrollToBottom: function () {
    // 每次点击按钮时，将 scrollTop 设置为一个较大的固定值
    this.setData({
      scrollTop: this.data.scrollTop + 100000000000000000, // 设置一个较大的值，确保滚动到底部
      showScrollToBottomButton: false
    });
  },
  onScroll: function (event) {
    const scrollTop = event.detail.scrollTop;
    const scrollHeight = event.detail.scrollHeight;

    // 使用 createSelectorQuery 获取scroll-view的clientHeight
    const query = wx.createSelectorQuery();
    query.select('#chatMessages').boundingClientRect(rect => {
      const clientHeight = rect.height;
      // 判断是否滚动到底部
      if (scrollTop + clientHeight + 100 >= scrollHeight) {
        this.setData({
          showScrollToBottomButton: false
        });
      } else {
        this.setData({
          showScrollToBottomButton: true
        });
      }
    }).exec();
  },
  toggleVoice(event) {
    const content = event.currentTarget.dataset.content; // 当前点击的文本内容
    const id = event.currentTarget.id; // 当前点击文本的唯一ID

    if (this.data.isPlaying && this.data.currentPlayingId === id) {
      // 如果正在播放，并且点击的是同一个文本，则暂停
      this.audioContext.pause();
      this.setData({
        isPlaying: false,
        currentIcon: this.data.playIcon
      });
    } else {
      if (this.audioContext.src && this.data.currentPlayingId === id) {
        // 如果已经有src且是同一个文本，继续播放
        this.audioContext.play();
        this.setData({
          isPlaying: true,
          currentIcon: this.data.pauseIcon
        });
      } else {
        // 如果是不同的文本或首次播放
        audioUtils.textToSpeech(content)
          .then((data) => {
            const taskId = data.task_id;
            return new Promise((resolve) => {
              setTimeout(() => resolve(taskId), 10000); // 延迟10秒
            });
          })
          .then((taskId) => {
            return audioUtils.querySpeechResult(taskId);
          })
          .then((result) => {
            const mp3_url = result.tasks_info[0].task_result.speech_url;
            this.audioContext.src = mp3_url; // 设置新的音频源
            this.audioContext.play();
            
            this.setData({
              isPlaying: true,
              currentIcon: this.data.pauseIcon,
              currentPlayingId: id // 更新当前播放的文本ID
            });
          })
          .catch((error) => {
            console.error('操作失败', error);
          });
      }
    }
  }
});